# @Author     ：SEED
# @DateTime   ：2019-09-24  19:43 
# @FileName   ：git_tools.py

import subprocess


class GitTools(object):

    @staticmethod
    def log(path, branch=None):
        """
        通过筛选git日志获取版本
        :param path: 本地工作路径
        :param branch: 分支名称
        :return:
        """
        version_list = []
        if branch:
            cmd = "cd {path} && git log {bName} --pretty=format:'%h|%s|%cn|%ci|%H' -n 50".format(path=path,
                                                                                                 bName=branch,
                                                                                                 )
        else:
            cmd = "cd {path} && git log --pretty=format:'%h|%s|%cn|%ci|%H' -n 50".format(path=path)
        p = subprocess.Popen(cmd, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                             shell=True)
        result, status = p.communicate()
        if status == None:
            for log in result.split('\n'):
                log = log.split('|')
                data = dict()
                data['ver'] = log[0]
                data['desc'] = log[1]
                data['user'] = log[2]
                data['comid'] = log[4]
                version_list.append(data)
        return version_list

    @staticmethod
    def branch(path):
        """
        获取分支列表
        :param path: 本地工作路径
        :return: list
        """
        branch_list = []
        cmd = "cd {path} && git branch".format(path=path)
        status, result = subprocess.getstatusoutput(cmd)
        if status == 0:
            for ds in result.split('\n'):
                if len(ds) == 0: continue
                data = dict()
                if ds.find('*') >= 0:
                    data['status'] = 1
                else:
                    data['status'] = 0
                data['name'] = ds.replace('* ', '').strip()
                data['value'] = ds.replace('* ', '').strip()
                branch_list.append(data)
        return branch_list

    @staticmethod
    def tag(path):
        """
        获取GIT标签列表
        :param path: 本地工作路径
        :return: list
        """
        tag_list = []
        cmd = "cd {path} && git tag".format(path=path)
        status, result = subprocess.getstatusoutput(cmd)
        if status == 0:
            for ds in result.split('\n'):
                if len(ds) == 0: continue
                data = dict()
                if ds.find('*') >= 0:
                    data['status'] = 1
                else:
                    data['status'] = 0
                data['name'] = ds.replace('* ', '').strip()
                data['value'] = ds.strip()
                tag_list.append(data)
        return tag_list
